
import classnames from 'classnames';
import styles from './index.module.less';
import React from 'react';

export interface IRangeNumberProps {
    value?: [number | undefined, number | undefined];
    onChange?: (value: [number | undefined, number | undefined]) => void;
}

export function RangeNumber(props: IRangeNumberProps) {

    const [value, setValue] = React.useState(formatValue(props.value));
    const [i1, setI1] = React.useState<string | undefined>(undefined);
    const [i2, setI2] = React.useState<string | undefined>(undefined);

    const onChange0 = React.useCallback((e?: string) => {
        if (e) {
            const v = parseFloat(e);
            if (isNaN(v)) {
                setValue([undefined, value[1]])
                setI1('');
                props.onChange?.([undefined, value[1]]);
            } else {
                setValue([v, value[1]]);
                setI1(v.toString());
                props.onChange?.([v, value[1]]);
            }
        } else {
            setValue([undefined, value[1]]);
            props.onChange?.([undefined, value[1]]);
        }
    }, [props, value]);

    const onChange1 = React.useCallback((e?: string) => {
        if (e) {
            const v = parseFloat(e);
            if (isNaN(v)) {
                setValue([value[0], undefined])
                setI2('');
                props.onChange?.([value[0], undefined]);
            } else {
                setValue([value[0], v]);
                setI2(v.toString());
                props.onChange?.([value[0], v]);
            }
        } else {
            setValue([value[0], undefined]);
            props.onChange?.([value[0], undefined]);
        }
    }, [props, value]);

    React.useEffect(() => {
        setValue(formatValue(props.value));
    }, [props.value]);

    return (
        <div className={classnames(styles['range-number'])}>
            <input
                value={i1}
                onChange={e => { setI1(e.target.value) }}
                onBlur={e => { onChange0(e.target.value) }}
            />
            <span>~</span>
            <input
                value={i2}
                onChange={e => { setI2(e.target.value) }}
                onBlur={e => { onChange1(e.target.value) }}
            />
        </div>
    )
}

/** 格式化 value */
function formatValue(value?: [number | undefined, number | undefined]) {
    if (!value) return [undefined, undefined];
    return [value[0], value[1]];
}